package com.lvtn.adsonandroid;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.lvtn.adsonandroid.GalleryViewActivity.GetImages;
import com.lvtn.adsonandroid.GalleryViewActivity.ImageAdapter;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class DetailNewsActivity extends Activity {
	 private static String GetImages = "http://10.0.2.2/android/getImages.php";
	 private static String URL = "http://10.0.2.2/android/news_upload/";
	 private ProgressDialog pDialog;
	 JSONParser jParser = new JSONParser();
	 ArrayList<HashMap<String, String>> data;
	 JSONArray data_array = null;
	 private String news_id; 
	 private Context ctx;
	 ImageView imageView;
	 Gallery ga;
	 public ImageLoader imageLoader; 
	 private String title;
	 private String detail;
	 private String date;
	 private String user;
	 private String link;
	 private String email;
	 private String email_com;
	 private TextView tieude;
	 private TextView chitiet;
	 private TextView ngaythang;
	 private TextView ten;
	 private ImageLoader imageloader;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detail_news);
		Intent t = getIntent();
		title = t.getStringExtra("title");
		detail = t.getStringExtra("detail");
		news_id = t.getStringExtra("news_id");
		date = t.getStringExtra("date");
		user = t.getStringExtra("user_name");
		link = t.getStringExtra("link");
		email = t.getStringExtra("user_email");
		email_com = t.getStringExtra("email_comuser");
		Log.d("linkamge",link);
		//title = t.getStringExtra("title");
		tieude = (TextView)findViewById(R.id.title);
		ngaythang = (TextView)findViewById(R.id.date);
		chitiet = (TextView)findViewById(R.id.detail);
		ten = (TextView)findViewById(R.id.user_name);
		tieude.setText(title);
		ngaythang.setText(date);
		chitiet.setText(detail);
		ten.setText(user);
		Log.d("tenuser",user);
		//new DownloadImageTask((ImageView) findViewById(R.id.image)).execute(link);
		imageloader = new ImageLoader(getApplicationContext());
		imageloader.DisplayImage(link, (ImageView) findViewById(R.id.image));
		ctx=getApplicationContext();
		data = new ArrayList<HashMap<String, String>>();
		news_id = this.getIntent().getStringExtra("news_id");
		Log.d("id", news_id);
		imageLoader=new ImageLoader(ctx);
		ga = (Gallery)findViewById(R.id.gallery1);
		imageView = (ImageView)findViewById(R.id.imageView1);
	  //  ga.setAdapter(new ImageAdapter(this));
	     new GetImages().execute();
	     ga.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
						long arg3) {
				  //  Log.d("tham so arg2",Integer.toString(arg2));
				//	HashMap<String, String> image = new HashMap<String, String>();
		           // image = data.get(arg2);
		         //   imageLoader.DisplayImage(image.get("link"), imageView);
					
				}
	        	
	        });
	}
	class GetImages extends AsyncTask<String, String, String> {
		

		/**
		* Before starting background thread Show Progress Dialog
		* */
			@Override
			protected void onPreExecute() {
				Log.d("asdasdasda","adasdada");
				super.onPreExecute();
				pDialog = new ProgressDialog(DetailNewsActivity.this);
				pDialog.setMessage("Loading...");
				pDialog.setIndeterminate(false);
				pDialog.setCancelable(false);
				pDialog.show();
			}
		/**
		* getting All record data from url
		* */
			protected String doInBackground(String... args) {
		// Building Parameters
			
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("tag","get_images"));
				params.add(new BasicNameValuePair("news_id", news_id));
				Log.d("id", news_id);
		// getting JSON string from URL
				JSONObject json = jParser.makeHttpRequest(GetImages, "GET", params);
		// Check your log cat for JSON reponse
				data_array = new JSONArray();
				Log.d("getImages: ", json.toString());
				try {
		// Checking for SUCCESS TAG
					int success = json.getInt("success");
					if (success == 1) {
				// Ada record Data (SUCCESS = 1)
				// Getting Array of daftar_rs
						data_array = json.getJSONArray("images");
				// looping through All daftar_rs
						for (int i = 0; i < data_array.length(); i++) {
							JSONObject c = data_array.getJSONObject(i);
					// Storing each json item in variable
							String id = c.getString("id");
							String email = c.getString("user_email");
							String link = URL + c.getString("name");
							String news_id = c.getString("news_id");
							String avatar = c.getString("avatar");
							
							HashMap<String, String> map = new HashMap<String, String>();
							map.put("id", id);
							map.put("link", link);
							map.put("user_email", email);
							map.put("news_id", news_id);
							map.put("avatar", avatar);
							
					// adding HashList to ArrayList
							data.add(map);
						}
					} else {
			
						return null;
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			return null;
			}
		/**
		* After completing background task Dismiss the progress 
		dialog
		* **/
			protected void onPostExecute(String file_url) {
		
				if (null != pDialog && pDialog.isShowing()) {
				pDialog.dismiss();
				}
				if(null == data || data.size() == 0){
					Toast toast = Toast.makeText(getApplicationContext(), "Không có hình nào cả", Toast.LENGTH_SHORT);
					toast.show();
				}
				else{
			// updating UI from Background Thread
					
				    ImageAdapter objAdapter = new ImageAdapter(data);
				    ga.setAdapter(objAdapter);
				   // if (data.size()> 0){
				  //       HashMap<String, String> image0 = new HashMap<String, String>();
				  //       image0 = data.get(0);
				  //       imageLoader.DisplayImage(image0.get("link"), imageView);
				  //   }
				}
			}
	}
	public class ImageAdapter extends BaseAdapter {
		private ArrayList<HashMap<String, String>> data;
    	private ImageLoader imageLoader1; 
    	int imageBackground;
    	
    	public ImageAdapter( ArrayList<HashMap<String, String>> d) {
		//	ctx = a.getApplicationContext();
			TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
		//	activity = a;
		    data=d;
			imageBackground = ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
			ta.recycle();
		}

		@Override
    	public int getCount() {
    		
    		return data.size();
    	}

    	@Override
    	public Object getItem(int arg0) {
    		
    		return arg0;
    	}

    	@Override
    	public long getItemId(int arg0) {
    		
    		return arg0;
    	}

    	@SuppressWarnings("deprecation")
		@Override
    	public View getView(int arg0, View arg1, ViewGroup arg2) {
    		ImageView iv = (ImageView) arg1;
    		if (iv == null) {
				iv = (ImageView) getLayoutInflater().inflate(R.layout.item_gallery_image, arg2, false);
			}
    		HashMap<String, String> image = new HashMap<String, String>();
            image = data.get(arg0);
    		//String link = image.get("link");
    		//Log.d("link","IMAGELOADER");
    		imageLoader1 = new ImageLoader(ctx);
    		imageLoader1.DisplayImage(image.get("link"), iv);
    		Log.d("link",image.get("link"));
    		iv.setScaleType(ImageView.ScaleType.FIT_XY);
    		iv.setLayoutParams(new Gallery.LayoutParams(300,240));
    		iv.setBackgroundResource(imageBackground);
    		return iv;
    	}

    }
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.detail_news, menu);
		return true;
	}

}
